<template>
  <div class="confirm-box">
    <el-dialog width="400px" :title="dialogTitle" v-model="dialogFormVisible" :draggable="true" @close="dialogClose">
      <div>
        <p>{{ msg }}</p>
      </div>
      <div v-if="isNeedPass" style="margin-top:20px">
        <el-form ref="dialogFormRef" :model="dialogForm" :rules="dialogFormRules">
          <el-form-item prop="password">
            <el-input v-model="dialogForm.password" type="password" show-password placeholder="为保证本次操作安全，请输入登录密码"
              @keypress.enter="submitHandle" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitHandle">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { nextTick, reactive, ref, toRefs } from 'vue'
import hexMD5 from "@/utils/md5.min.js"
import api from './api'
export default {
  setup(props, context) {
    const dialogFormRef = ref(null)

    const state = reactive({
      isNeedPass: true,
      dialogFormVisible: false,
      dialogTitle: '',
      msg: '',
      dialogForm: {},
      dialogFormRules: {
        password: [
          { required: true, message: '为保证本次操作安全，请输入登录密码', trigger: 'blur' },
        ],
      },
    })

    function dialogShow(title, msg, isNeedPass = true) {
      state.isNeedPass = isNeedPass
      state.dialogTitle = title
      state.msg = msg
      state.dialogFormVisible = true
    }

    function submitHandle() {
      if (state.isNeedPass) {
        dialogFormRef.value.validate((valid, fields) => {
          if (valid) {
            formSumbit(state.dialogForm.password)
          }
        })
      } else {
        context.emit('verification')
        state.dialogFormVisible = false
      }
    }

    function formSumbit(password) {
      const obj = {
        password: hexMD5(password)
      }
      api.confirmPassword(obj).then(res => {
        if (res.code == '200') {
          context.emit('verification')
          state.dialogFormVisible = false
        } else {
          warningDeal(res.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    }

    function dialogClose() {
      dialogFormRef.value && dialogFormRef.value.resetFields()
    }

    return {
      ...toRefs(state),
      dialogFormRef,
      dialogShow,
      submitHandle,
      dialogClose,
    }
  }
}
</script>

<style>
</style>